package com.vesystem.vegua.utils;

import com.vesystem.vegua.exceptionConfig.ErrorCode;
import com.vesystem.vegua.exceptionConfig.ParameterInvalid;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @auther hcy
 * @create 2020-12-08 16:50
 * @Description
 */
public class JwtToken {
    public static final String TOKEN_HEADER = "Authorization";
    public static final long REFRESH_TIME = 1800L;//1800L,30分钟刷新一次
    private static final String SecretKey =  "hechongyang";


    /**
     * 构建token
     * @param loginname
     * @param role
     * @return
     */
    public static String createToken(String loginname,Integer id,Integer role){
        final Date createdDate = new Date();
        final Date expirationDate = new Date(createdDate.getTime() + REFRESH_TIME * 1000);
        Map<String,Object> map = new HashMap<>(4);
        map.put("ROLE",role);
        map.put("ID",id);
        return Jwts.builder()
                .setHeaderParam("type","JWT")
                .signWith( SignatureAlgorithm.HS512,SecretKey)
                .setClaims(map)
                .setSubject( loginname )
                .setIssuedAt( createdDate )
                .setExpiration( expirationDate )
                .compact();
    }

    /**
     * 盘点token是否已经过期
     * @param request
     * @return
     */
    public static boolean isTokenExpired(HttpServletRequest request){
        String token = request.getHeader(TOKEN_HEADER);
        Date expiredDate = getTokenBody(token).getExpiration();
        return expiredDate.before(new Date());
    }

    /**
     * 获取token中的用户名
     * @param token
     * @return
     */
    public static String getUserLoginname(String token){
        Claims claims = getTokenBody(token);
        return claims.getSubject();
    }

    private static Claims getTokenBody(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SecretKey)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (ExpiredJwtException e){
            throw new ParameterInvalid(ErrorCode.TOKEN_EXPIRED);
        }
    }

    /**
     * 刷新令牌
     * @param request
     * @return
     */
    public static String refreshToken(HttpServletRequest request){
        String token = request.getHeader(TOKEN_HEADER);
        Claims claims = getTokenBody(token);
        claims.setExpiration(new Date(System.currentTimeMillis() + REFRESH_TIME * 1000));
        return createToken(claims.getSubject(),
                Integer.valueOf(claims.get("ID").toString()),
                        Integer.valueOf(claims.get("ROLE").toString()));
    }

    public static Claims getClaims(String token){
        return getTokenBody(token);
    }


    /**
     * 获取登录名
     * @param request
     * @return
     */
    public static String getUserLoginname(HttpServletRequest request){
        String token = request.getHeader(TOKEN_HEADER);
        Claims claims = getTokenBody(token);
        return claims.getSubject();
    }

    /**
     * 获取到用户角色id
     * @param request
     * @return
     */
    public static Integer getUserRoleId(HttpServletRequest request){
        String token = request.getHeader(TOKEN_HEADER);
        Claims claims = getTokenBody(token);
        return Integer.valueOf(claims.get("ROLE").toString());
    }

    /**
     * 获取到用户id
     * @param token
     * @return
     */
    public static Integer getUserId(String token){
        Claims claims = getTokenBody(token);
        return Integer.valueOf(claims.get("ID").toString());
    }

    /**
     * 获取到用户id
     * @param request
     * @return
     */
    public static Integer getUserId(HttpServletRequest request){
        String token = request.getHeader(TOKEN_HEADER);
        return getUserId(token);
    }


}
